package com.ruoyi.paint.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.paint.admin.domain.Dto.ImportSummary;
import com.ruoyi.paint.admin.domain.ImExportDto.TqCarsImport;
import com.ruoyi.paint.admin.domain.ImExportDto.TqColorschemesImport;
import com.ruoyi.paint.admin.domain.ImExportDto.TqSchemetintsAllImport;
import com.ruoyi.paint.admin.domain.ImExportDto.TqSchemetintsImport;
import com.ruoyi.paint.admin.domain.TqCars;
import com.ruoyi.paint.admin.domain.result.ImportResult;
import com.ruoyi.paint.admin.listener.CarDataListener;
import com.ruoyi.paint.admin.listener.ColorSchemeListener;
import com.ruoyi.paint.admin.listener.SchemeTintsAllListener;
import com.ruoyi.paint.admin.listener.SchemeTintsDataListener;
import com.ruoyi.paint.admin.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 汽车信息导入导出
 * @author itchen
 * @date 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/paint/cars")
public class TqCarsImportController {
    @Autowired
    private ITqCarsService tqCarsService;
    @Autowired
    private TqColorschemesService tqColorschemesService;

    @Autowired
    private TqTintsService tqTintsService;
    @Autowired
    private TqSchemetintsService tqSchemetintsService;
    @Autowired
    private ICxcarService iCxcarService;

    /**
     * 导入数据
     * @param file
     * @return
     * @throws IOException
     */
//    @Anonymous
    @PostMapping("/importExcel")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        Map<String,List<String>> failureMessages = new HashMap<>();
        ImportSummary summary = new ImportSummary();
        ImportCallback callback = new ImportCallback() {
            @Override
            public AjaxResult onCompleted(ImportSummary importSummary) {
                return generateResponse(importSummary);
            }
        };
        // 监听器实例化，但不直接执行保存操作
        CarDataListener carDataListener = new CarDataListener(tqCarsService, summary, "车辆信息表格", callback);
        ColorSchemeListener colorSchemeListener = new ColorSchemeListener(tqColorschemesService, tqCarsService, summary, "配色方案表格", callback);
        SchemeTintsDataListener schemeTintsDataListener = new SchemeTintsDataListener(tqSchemetintsService, tqColorschemesService, tqCarsService, tqTintsService, summary, "配色和色母表格", callback);

        try (ExcelReader reader = EasyExcel.read(file.getInputStream()).build()) {
            ReadSheet[] sheets = new ReadSheet[]{
                    EasyExcel.readSheet(0).head(TqCarsImport.class).registerReadListener(carDataListener).build(),
                    EasyExcel.readSheet(1).head(TqColorschemesImport.class).registerReadListener(colorSchemeListener).build(),
                    EasyExcel.readSheet(2).head(TqSchemetintsImport.class).registerReadListener(schemeTintsDataListener).build()
            };

            reader.read(sheets);
            // 在这里处理监听器收集的数据并保存到数据库
//            List<TqCars> collectedCar = carDataListener.getCollectedCar();
            ExcelUtil<TqCars> util = new ExcelUtil<TqCars>(TqCars.class);
            List<TqCars> collectedCar = util.importExcel(file.getInputStream());
            int stringsCar = tqCarsService.saveBatchCar(collectedCar, file);

            List<TqColorschemesImport> collectedData = colorSchemeListener.getCollectedData();
            //保存配色方案
            List<String> stringsScheme = tqColorschemesService.saveBatchService(collectedData);
            //保存色母和关联表数据
            List<TqSchemetintsImport> collectedSchemeTint = schemeTintsDataListener.getCollectedSchemeTint();
            List<String> strings = tqSchemetintsService.saveBatchSchemeTint(collectedSchemeTint);
            reader.finish();

        } catch (Exception e) {
            log.error("导入Excel文件时发生错误", e);
           return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(failureMessages);
    }


    private AjaxResult generateResponse(ImportSummary summary) {
        if (summary.getTotalSuccessCount() == 0 || summary.hasFailures()) {
            StringBuilder errorMsg = new StringBuilder("导入结果：\n");
            for (Map.Entry<String, ImportResult> entry : summary.getSheetResults().entrySet()) {
                errorMsg.append(entry.getKey()).append(": 成功 ").append(entry.getValue().getSuccessCount()).append(" 条\n");
                if (!entry.getValue().getFailureMessages().isEmpty()) {
                    errorMsg.append("失败原因：").append(String.join(", ", entry.getValue().getFailureMessages())).append("\n");
                }
            }
            return AjaxResult.error(errorMsg.toString());
        } else {
            return AjaxResult.success("导入成功，共导入 " + summary.getTotalSuccessCount() + " 条记录。");
        }
    }


    /**
     * 两个表的
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/new/importExcel")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importExcelAll(@RequestParam("file") MultipartFile file){
        Map<String,List<String>> failureMessages = new HashMap<>();
        ImportSummary summary = new ImportSummary();
        StringBuilder stringBuilder =  new StringBuilder();

        ImportCallback callback = new ImportCallback() {
            @Override
            public AjaxResult onCompleted(ImportSummary importSummary) {
                return generateResponse(importSummary);
            }
        };
        // 监听器实例化，但不直接执行保存操作
        CarDataListener carDataListener = new CarDataListener(tqCarsService, summary, "车辆信息表格", callback);
        SchemeTintsAllListener schemeTintsDataListener = new SchemeTintsAllListener(tqSchemetintsService, tqColorschemesService, tqCarsService, tqTintsService, summary, "配色和色母表格", callback);

        try (ExcelReader reader = EasyExcel.read(file.getInputStream()).build()) {
            ReadSheet[] sheets = new ReadSheet[]{
                    EasyExcel.readSheet(0).head(TqCarsImport.class).registerReadListener(carDataListener).build(),
                    EasyExcel.readSheet(1).head(TqSchemetintsAllImport.class).registerReadListener(schemeTintsDataListener).build()
            };

            reader.read(sheets);
            // 在这里处理监听器收集的数据并保存到数据库
            ExcelUtil<TqCars> util = new ExcelUtil<TqCars>(TqCars.class);
            List<TqCars> collectedCar = util.importExcel(file.getInputStream());
            int num = tqCarsService.saveBatchCar(collectedCar, file);
            //保存色母和关联表数据
            List<TqSchemetintsAllImport> collectedSchemeTintAll = schemeTintsDataListener.getCollectedSchemeTintAll();
//            //保存配色方案
            int stringBuilder1 = tqColorschemesService.saveBatchServiceAll(collectedSchemeTintAll);
            String strings = tqSchemetintsService.saveBatchSchemeTintAll(collectedSchemeTintAll);
            reader.finish();
             stringBuilder.append("汽车信息表导入数量："+num).append("配色关联表导入数量："+strings).append("配色方案导入数量："+stringBuilder1);
        } catch (Exception e) {
            log.error("导入Excel文件时发生错误", e);
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(stringBuilder.toString());
    }





}
